﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using LiWi;

namespace LiWi
{
    public partial class ConnectForm : Form
    {

        WindowsAdapt adapt = new WindowsAdapt();
        public ConnectForm()
        {
            InitializeComponent();
            adapt.SetForm(this);
            label5.Text = "注意：Bas文件在根目录，\r\n文件名为“总线通讯简化版.bas”,\r\n轴映射到Axis0，操控Axis0控制总线轴";
            //IP刷新
            comboBox_ipList.Items.Clear();
            byte[] ipList = new byte[512];
            Shell.PMC_SearchEthlist(ipList, 512, 200);
            string str = System.Text.ASCIIEncoding.Default.GetString(ipList);

            string[] ipArray = str.Split('\0');
            foreach (string item in ipArray)
            {
                if (item.Length > 0)
                {
                    comboBox_ipList.Items.Add(item);
                    comboBox_ipList.Text = item.ToString();
                }
            }

        }

        private void buttonIpConnect_Click(object sender, EventArgs e)
        {
            if (Data.handle == (IntPtr)0)
            {
                if (!IsValidIP(comboBox_ipList.Text))
                {
                    MessageBox.Show("Ip地址不正确");
                    return;
                }
                int ret = Shell.PMC_OpenEth(comboBox_ipList.Text, ref Data.handle);
                if (ret == 0 && Data.handle != (IntPtr)0)
                {
                    buttonIpConnect.Text = "已连接";
                    buttonPciConnect.Text = buttonIpConnect.Text;
                    buttonComConnect.Text = buttonIpConnect.Text;
                    buttonPciConnect.Enabled = false;
                    buttonComConnect.Enabled = false;
                    buttonIpConnect.Enabled = true;

                    openEnable();
                }
                else
                {
                    buttonIpConnect.Text = "连接";
                    buttonPciConnect.Text = buttonIpConnect.Text;
                    buttonComConnect.Text = buttonIpConnect.Text;
                    buttonPciConnect.Enabled = true;
                    buttonComConnect.Enabled = true;
                    buttonIpConnect.Enabled = true;
                }
            }
            else
            {
                Shell.PMC_Close(Data.handle);
                Data.handle = (IntPtr)0;
                buttonIpConnect.Text = "连接";
                buttonPciConnect.Text = buttonIpConnect.Text;
                buttonComConnect.Text = buttonIpConnect.Text;
                buttonPciConnect.Enabled = true;
                buttonComConnect.Enabled = true;
                buttonIpConnect.Enabled = true;
                
            }
        }

        private void buttonPciConnect_Click(object sender, EventArgs e)
        {
            //if (Data.handle == (IntPtr)0)
            //{

            //    int ret = Shell.pmc_OPEN(comboBox_ipList.Text, ref Data.handle);
            //    if (ret == 0 && Data.handle != (IntPtr)0)
            //    {
            //        buttonIpConnect.Text = "已连接";
            //        buttonPciConnect.Text = buttonIpConnect.Text;
            //        buttonComConnect.Text = buttonIpConnect.Text;
            //        buttonPciConnect.Enabled = false;
            //        buttonComConnect.Enabled = false;
            //        buttonIpConnect.Enabled = true;
            //thEnable = new Thread(readEnable);
            //thEnable.Start();
            //        openEnable();
            //    }
            //    else
            //    {
            //        buttonIpConnect.Text = "连接";
            //        buttonPciConnect.Text = buttonIpConnect.Text;
            //        buttonComConnect.Text = buttonIpConnect.Text;
            //        buttonPciConnect.Enabled = true;
            //        buttonComConnect.Enabled = true;
            //        buttonIpConnect.Enabled = true;
            //    }
            //}
            //else
            //{
            //    Shell.PMC_Close(Data.handle);
            //    Data.handle = (IntPtr)0;
            //    buttonIpConnect.Text = "连接";
            //    buttonPciConnect.Text = buttonIpConnect.Text;
            //    buttonComConnect.Text = buttonIpConnect.Text;
            //    buttonPciConnect.Enabled = true;
            //    buttonComConnect.Enabled = true;
            //    buttonIpConnect.Enabled = true;
            //}
        }

        private void buttonComConnect_Click(object sender, EventArgs e)
        {
            if (Data.handle == (IntPtr)0)
            {
                if (comboBoxCOM.Text.Length <= 0)
                {
                    MessageBox.Show("未选择有效的Com口");
                    return;
                }
                int ret = Shell.PMC_OpenCom(Convert.ToUInt16(comboBoxCOM.Text), ref Data.handle);
                if (ret == 0 && Data.handle != (IntPtr)0)
                {
                    buttonIpConnect.Text = "已连接";
                    buttonPciConnect.Text = buttonIpConnect.Text;
                    buttonComConnect.Text = buttonIpConnect.Text;
                    buttonPciConnect.Enabled = false;
                    buttonComConnect.Enabled = false;
                    buttonIpConnect.Enabled = true;

                    openEnable();
                }
                else
                {
                    buttonIpConnect.Text = "连接";
                    buttonPciConnect.Text = buttonIpConnect.Text;
                    buttonComConnect.Text = buttonIpConnect.Text;
                    buttonPciConnect.Enabled = true;
                    buttonComConnect.Enabled = true;
                    buttonIpConnect.Enabled = true;
                }
            }
            else
            {
                Shell.PMC_Close(Data.handle);
                Data.handle = (IntPtr)0;
                buttonIpConnect.Text = "连接";
                buttonPciConnect.Text = buttonIpConnect.Text;
                buttonComConnect.Text = buttonIpConnect.Text;
                buttonPciConnect.Enabled = true;
                buttonComConnect.Enabled = true;
                buttonIpConnect.Enabled = true;
            }
        }



        public bool IsValidIP(string ip)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(ip, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
            {
                string[] ips = ip.Split('.');
                if (ips.Length == 4 || ips.Length == 6)
                {
                    if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
                        return true;
                    else
                        return false;
                }
                else
                    return false;

            }
            else
                return false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int[] enable = { 0, 0, 0, 0, 0 };
            if (Data.handle != (IntPtr)0)
            {
                for (int i = 0; i < 5; i++)
                {
                    int fag = 0;
                    Shell.PMC_GetAxisEnable(Data.handle, i, ref fag);
                    var Out_Num = "btnEnable_" + i;
                    var OUTNum = this.Controls.Find(Out_Num, true).FirstOrDefault() as Button;
                    if (enable[i] != fag)
                    {

                        if (fag == 0)
                        {
                            OUTNum.Text = $"轴{i}开使能";
                            OUTNum.BackColor = Color.White;
                        }
                        else
                        {
                            OUTNum.Text = $"轴{i}关使能";
                            OUTNum.BackColor = Color.LightGray;
                        }
                        enable[i] = fag;
                    }

                }
            }
        }

        private void ConnectForm_Load(object sender, EventArgs e)
        {

        }


        private void comboBox_ipList_DropDown(object sender, EventArgs e)
        {
        //    comboBox_ipList.Items.Clear();
        //    byte[] ipList = new byte[512];
        //    Shell.PMC_SearchEthlist(ipList, 512, 200);
        //    string str = System.Text.ASCIIEncoding.Default.GetString(ipList);

        //    string[] ipArray = str.Split('\0');
        //    foreach (string item in ipArray)
        //    {
        //        if (item.Length > 0)
        //        {
        //            comboBox_ipList.Items.Add(item);
        //            comboBox_ipList.Text = item.ToString();
        //        }
        //    }
        }


        private void comboBoxCOM_DropDown(object sender, EventArgs e)
        {
            string[] ArryPort = SerialPort.GetPortNames();
            comboBoxCOM.Items.Clear();
            foreach (string str in ArryPort)
            {
                comboBoxCOM.Items.Add(str);
            }
        }

        //使能开关
        public void openEnable()
        {
            for (int i = 0; i < 5; i++)
            {
                int num = i;
                var Out_Num = "btnEnable_" + i;
                var OUTNum = this.Controls.Find(Out_Num, true).FirstOrDefault() as Button;
                OUTNum.Click += (sender, e) =>
                {

                    if (Data.handle != (IntPtr)0)
                    {
                        if (OUTNum.Text == $"轴{num}开使能")
                        {
                            OUTNum.Text = $"轴{num}关使能";
                            OUTNum.BackColor = Color.LightGray;
                            Shell.PMC_SetAxisEnable(Data.handle, num, 1);
                            Shell.PMC_SetAtype(Data.handle, num, 1);
                        }
                        else
                        {
                            OUTNum.Text = $"轴{num}开使能";
                            OUTNum.BackColor = Color.White;
                            Shell.PMC_SetAxisEnable(Data.handle, num, 0);
                        }
                    }
                };
            }
        }




        ~ConnectForm()
        {
            Shell.PMC_Rapidstop(Data.handle, 3);
            Shell.PMC_Close(Data.handle);
            Data.handle = (IntPtr)0;
        }

        private void OpenCanFile_Click(object sender, EventArgs e)
        {
            if (Data.handle != (IntPtr)0)
            {
                string strFileName = "";
                if (OpenCanFile.Text == "打开并连接")
                {
                    #region 打开文件
                    OpenFileDialog ofd = new OpenFileDialog();
                    ofd.Filter = "Bas文件(*.bas)|*.bas|所有文件|*.*";
                    ofd.ValidateNames = true;   //验证用户输入的是否是一个有效的Windows文件名
                    ofd.CheckFileExists = true; //验证路径的有效性
                    ofd.CheckPathExists = true;
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        strFileName = ofd.FileName;
                    }
                    #endregion

                    #region 连接总线
                    var ret = Shell.PMC_BasDown(Data.handle, strFileName, 1);
                    OpenCanFile.Text = "连接中";
                    OpenCanFile.Enabled = false;
                    //System.Threading.Thread.Sleep(1000);

                    if (ret != 0)
                    {
                        OpenCanFile.Text = "打开并连接";
                        OpenCanFile.Enabled = true;
                        MessageBox.Show("总线连接失败");
                    }
                    else
                    {
                        int[] connectflag = { 0 };
                        int num = 0;
                        for (int i = 0; i < 10; i++)
                        {
                            Shell.PMC_GetVariableInt(Data.handle, "connectFlag", 2, connectflag, ref num);
                            if (connectflag[0] != 1)
                            {
                                OpenCanFile.Text = $"连接中。。。{i}";
                                System.Threading.Thread.Sleep(1000);
                            }
                            else
                            {
                                OpenCanFile.Text = "连接成功";
                                OpenCanFile.Enabled = false;
                                MessageBox.Show("总线连接成功");
                                return;
                            }
                        }
                        OpenCanFile.Text = "打开并连接";
                        OpenCanFile.Enabled = true;
                        MessageBox.Show("总线连接失败");

                    }
                    #endregion
                }
                else OpenCanFile.Text = "打开并连接";
            }
            else MessageBox.Show("请先连接控制器！！！");
        }
    }
}
